import React, { useState } from "react";
import { Breadcrumbs, BreadcrumbItem } from "@nextui-org/react";
import { useRouter } from "next/router";
import { capitalize } from "@/utils/base";
import { useHttp } from "@/hooks";
import useMounted from "@/hooks/useMounted";

type AppItem = {
  id: number;
  name: string;
  introduce: string;
  type: string;
};

export default function Breadbar() {
  const router = useRouter();
  const { http } = useHttp();
  const [appList, setAppList] = useState([] as AppItem[]);

  const getAppList = async () => {
    const res = await http.get("/api/app/simpleList");
    console.log("🚀 ~ getAppList ~ res:", res);
    if (res?.success) {
      setAppList(res.data as AppItem[]);
    }
  };

  useMounted(() => {
    getAppList();
  });

  if (
    router.pathname === "/" ||
    router.pathname === "" ||
    router.pathname.startsWith("/user/")
  ) {
    return null;
  }

  let pathname = router.pathname;
  const parts = router.pathname
    .split("/")
    .map((part) => capitalize(part ?? ""));
  const lastPath = parts[parts.length - 1];

  return (
    <Breadcrumbs className="w-full px-6 py-2">
      <BreadcrumbItem href="/">Home</BreadcrumbItem>
      {["Endpoints", "Configs", "Datasets"].includes(lastPath) && (
        <BreadcrumbItem href="/apps">Apps</BreadcrumbItem>
      )}
      {lastPath === "Endpoints" && appList.length && (
        <BreadcrumbItem href={"/datasets" + `?appid=${appList[0].id}`}>
          Datasets
        </BreadcrumbItem>
      )}
      <BreadcrumbItem>{lastPath}</BreadcrumbItem>
    </Breadcrumbs>
  );
}
